'use strict';

const Service = require('egg').Service;
const Mock = require('mockjs');
const dayjs = require('dayjs');
dayjs().format()

class SearchService extends Service {
  async getList() {
    const {
      ctx,
      app
    } = this;
    const {
      pageSize,
      pageIndex,
      type,
      keyword,
      count
    } = ctx.query;
    let sql = `select * from search where 1=1 `;
    let countSql = `select count(id) as total from search where 1=1 `
    if (type) {
      sql += `and type="${type}" `
      countSql += `and type="${type}" `
    }
    if (keyword) {
      sql += `and keyword="${keyword}" `
      countSql += `and keyword="${keyword}" `
    }
    if (count) {
      sql += `and count="${count}" `
      countSql += `and count="${count}" `
    }
    if (pageSize && pageIndex) {
      sql += `limit ${(pageIndex-1)*pageSize},${pageSize} `
    }
    const res = await app.mysql.query(sql);
    const [{
      total
    }] = await app.mysql.query(countSql);
    return {
      data: res,
      total,
    }
  }
  async delSearch() {
    const {
      ctx,
      app
    } = this;
    const {
      id
    } = ctx.request.body;
    const res = await app.mysql.delete('search', {
      id
    });
    return res
  }
  async addSearch() {
    const {
      ctx,
      app
    } = this;
    const {
      keyword
    } = ctx.req.body;
    const info = await app.mysql.get('search',{
      keyword
    });
    if(info) {
      let row = {};
      row.id = info.id;
      row.count =  ++row.count;
      const res = await app.mysql.update('search',row);
      return res
    } else {
      const res = await app.mysql.insert('search',{
        keyword,
        count:1,
      });
      return res
    }
  }
}

module.exports = SearchService;